import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


def send_email(text, server="smtp.163.com", sender=None, receivers=None, psw=None, attachment=None, to="收件人",subject="python自动发送邮件"):
    """
    text:邮件内容
    server：发送邮件服务方，默认为163服务方
    sender：发送人
    receivers：接收人，多个接收人封装为列表
    psw：从163邮箱获取的服务密码
    attachment：附件，单个附件地址，或者多个附件地址列表
    to：收件人名称
    subject：邮件主题
    """
    # 实例化一个邮箱对象
    smtp = smtplib.SMTP()
    # 发送的文本内容
    text = f'<p>{text}</p>'
    # 实例化一个发送文本的邮箱对象
    mime_text = MIMEText(_text=text, _subtype="html", _charset="utf-8")
    # 发件人
    mime_text["from"] = sender
    # 收件人
    mime_text["to"] = to
    # 主题
    # mime_text["subject"] = subject
    # 创建一个多部分的邮箱对象
    mime_multipart = MIMEMultipart()
    # 邮箱主题
    mime_multipart['Subject'] = subject
    mime_multipart.attach(mime_text)
    if attachment:
        # 发送附件
        if isinstance(attachment, str):
            # 单个附件地址
            with open(attachment, 'rb') as f:
                mime_application = MIMEApplication(f.read())
                mime_application.add_header('Content-Disposition', 'attachment', filename=attachment)
                mime_multipart.attach(mime_application)
        elif isinstance(attachment, list):
            # 多个附件地址列表
            for file in attachment:
                with open(file, 'rb') as f:
                    mime_application = MIMEApplication(f.read())
                    mime_application.add_header('Content-Disposition', 'attachment', filename=file)
                    mime_multipart.attach(mime_application)
    try:
        # 连接并登录发送邮件的服务方
        smtp.connect(server)
        smtp.login(sender, password=psw)
        # 发送邮件
        smtp.sendmail(from_addr=sender, to_addrs=receivers, msg=mime_multipart.as_string())
        print("发送邮件到 ", receivers, " 成功！")
    except Exception as e:
        print(str(e))
    finally:
        smtp.quit()


if __name__ == '__main__':
    text = "Python自动发送邮件"
    sender = 'xxxxxxxxxxx@163.com'
    psw = 'xxxxxxxxxxxxxxxx'
    receivers = ["xxxxxxxxxx@qq.com", "xxxxxxxxxx@163.com"]
    # 不发送附件方式
    # send_email(text=text,sender=sender,psw=psw,receivers=receivers)
    # 发送单个附件
    # attachment = "./requirements.txt"
    # send_email(text=text,sender=sender,psw=psw,receivers=receivers,attachment=attachment)
    # 发送多个附件
    # attachment = ["./requirements.txt","./sspython.ico"]
    # send_email(text=text,sender=sender,psw=psw,receivers=receivers,attachment=attachment)
